<template>
  <div>
    <div>
      <div class="cacheArea">
        <div class="item" v-for="(item, index) in resultArr" :key="index">
          <div class="remove" @click="remove(index)"></div>
          <img :src="item">
        </div>
        <label :for="refId">
          <div class="item" v-if="resultArr.length < max"><img src="../assets/imgs/add.png"></div>
        </label>
      </div>
      <div class="cacheArea">
        <input type="file" :id="refId" accept="image/*" @change="upload" ref="fileInput" style="display:none">
      </div>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import Exif from "exif-js";
export default {
  name: "MyMulImage",
  props: {
    max: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      refId: 'refId' + parseInt(Math.random() * 10000000),
      resultArr: [],
    };
  },
  methods: {
    upload(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.imgPreview(files[0]);
    },
    imgPreview(file) {
      let self = this;
      let Orientation;
      // 去获取拍照时的信息，解决拍出来的照片旋转问题
      Exif.getData(file, function() {
        Orientation = Exif.getTag(this, "Orientation");
      });
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return;

      if (/^image/.test(file.type)) {
        // 创建一个reader
        let reader = new FileReader();
        // 将图片2将转成 base64 格式
        reader.readAsDataURL(file);
        // 读取成功后的回调
        reader.onloadend = function() {
          let result = this.result;
          let img = new Image();
          img.src = result;
          let imgSize = this.result.length;
          // 判断图片是否大于1MB,是就直接上传，反之压缩图片
          if (imgSize <= 1024 * 1024) {
            self.resultArr.push(this.result);
            self.$emit("imageReady", self.resultArr);
            self.postImg();
          } else {
            img.onload = function() {
              let data = self.compress(img, Orientation, file.type, 4194304 / imgSize);
              self.resultArr.push(data);
              self.$emit("imageReady", self.resultArr);
              self.postImg();
            };
          }
        };
      }
    },
    postImg() {
      // 这里写接口
    },
    remove: function (index) {
      this.resultArr.splice(index, 1);
      this.$refs.fileInput.value = '';
    },
    rotateImg(img, direction, canvas) {
      const min_step = 0;
      const max_step = 3;
      if (img == null) return;
      let height = img.height;
      let width = img.width;
      let step = 2;
      if (direction == "right") {
        step++;
        step > max_step && (step = min_step);
      } else {
        step--;
        step < min_step && (step = max_step);
      }
      let degree = step * 90 * Math.PI / 180;
      let ctx = canvas.getContext("2d");
      switch (step) {
        case 0:
          canvas.width = width;
          canvas.height = height;
          ctx.drawImage(img, 0, 0);
          break;
        case 1:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, 0, -height);
          break;
        case 2:
          canvas.width = width;
          canvas.height = height;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, -height);
          break;
        case 3:
          canvas.width = height;
          canvas.height = width;
          ctx.rotate(degree);
          ctx.drawImage(img, -width, 0);
          break;
      }
    },
    compress(img, Orientation, fileType, rate) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      let tCanvas = document.createElement("canvas");
      let tctx = tCanvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
      let ratio;
      if ((ratio = width * height / 4000000) > 1) {
        console.log("大于400万像素");
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      } else {
        ratio = 1;
      }
      canvas.width = width;
      canvas.height = height;
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      // 如果图片像素大于100万则使用瓦片绘制
      let count;
      if ((count = width * height / 1000000) > 1) {
        console.log("超过100W像素");
        count = ~~(Math.sqrt(count) + 1);
        let nw = ~~(width / count);
        let nh = ~~(height / count);
        tCanvas.width = nw;
        tCanvas.height = nh;
        for (let i = 0; i < count; i++) {
          for (let j = 0; j < count; j++) {
            tctx.drawImage(
              img,
              i * nw * ratio,
              j * nh * ratio,
              nw * ratio,
              nh * ratio,
              0,
              0,
              nw,
              nh
            );
            ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
          }
        }
      } else {
        ctx.drawImage(img, 0, 0, width, height);
      }
      if (Orientation != "" && Orientation != 1) {
        switch (Orientation) {
          case 6:
            this.rotateImg(img, "left", canvas);
            break;
          case 8:
            this.rotateImg(img, "right", canvas);
            break;
          case 3:
            this.rotateImg(img, "right", canvas);
            this.rotateImg(img, "right", canvas);
            break;
        }
      }
      let ndata = canvas.toDataURL(fileType, rate);
      console.log("压缩前：" + initSize);
      console.log("压缩后：" + ndata.length);
      console.log(
        "压缩率：" + ~~(100 * (initSize - ndata.length) / initSize) + "%"
      );
      tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
      return ndata;
    }
    // ,
    // initComponent: function () {
    //   this.resultArr = [];
    //   this.$refs.fileInput.value = '';
    // }
  }
};
</script>

<style lang="less" scoped>
.cacheArea {
  display: flex;
  .item {
    width: 90px;
    height: 90px;
    margin-right: 10px;
    position: relative;
    .remove {
      position: absolute;
      width: 24px;
      height: 24px;
      top: -8px;
      right: -8px;
      background: url(../assets/imgs/delete.png);
      background-size: 100%;
    }
    img {
      width: 100%;
      height: 100%;
    }
  }
}

</style>

